"""
-- coding: utf-8 --
@Time : 2023/8/1
@Author : 张书译
@Describe:获取JSON配置文件信息
"""
import json
import jsonpath
import config


class ReadJsonFile:
    """
    获取配置文件json
    """

    def __init__(self, path=config.config_json):
        self.path = path

    def read_json(self):
        with open(self.path, encoding='utf-8') as f:
            data = json.load(f)
        return data

    def get_value(self, key):
        data = self.read_json()
        return data[key]

    def write(self, key, value):
        dataN = self.read_json()
        dataN[key] = value
        with open(self.path, "w", encoding='utf-8') as f:
            json.dump(dataN, f, ensure_ascii=False, sort_keys=True, indent=4)

    def get_json(self, key, num=1, key2=None, data=None):
        """读取值"""
        if data is None:
            data = self.read_json()
        tier = '.' * num
        if key2 is None:
            value = jsonpath.jsonpath(data, f"${tier}{key}")
            return value
        else:
            value = jsonpath.jsonpath(data, f"$.{key2}{tier}{key}")
            return value

    def get_if_json(self, key1, key2, key3, va, num=0, data=None, key=None):
        """
        :param data: 分析数据json
        :param key: 最外层的key
        :param num: 第几层的数据默认为1
        :param key1: 上一层key
        :param key2: 判断的key
        :param key3: 获取那个值得key
        :param va: 对比的value
        :return: 返回获取的值
        """
        if data is None:
            data = self.read_json()[key]['data']
        if key1 == 'data':
            data = self.read_json()[key]
        tier = '.' * num
        value = jsonpath.jsonpath(data, f"$.{key1}{tier}[?(@.{key2} == '{va}')][{key3}]")
        return value


